#coding:utf8
'''
    视频相关
'''

from flask_restful import Resource, request
from _sys.parser import parsers
from _sys.models import MongodbOperations, ResponseJson, Token, CreateId, FormatIO
from _sys.code import dbNameDict
from _sys.function import allow_cross, admin_open_ips, had_power,format_words, parse_param_info

import time

mgOp = MongodbOperations()
responseJson = ResponseJson()
token = Token()
cId = CreateId()

class Video(Resource):
    '''
        /video
        -- get 获取视频列表 单个
        -- post 修改视频信息
        -- put 新增视频信息
        -- delete 删除视频信息
    '''
    @allow_cross
    def put(self):
        '''
            新增视频
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        title = args.get('title')  # 视频标题
        cn = args.get('cn')   # 视频文本
        en = args.get('en')
        tw = args.get('tw')
        link = args.get('link') # 链接
        status = args.get('status')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanAddVideo', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        v_id = cId.vid(format_words(parse_param_info(link))['cn'])   # 创建vid  md5确定一致性

        if mgOp.find_one(dbNameDict['videoData'], filter={'v_id':v_id}):   # 视频已存在
            return responseJson.error_response(code='resourcesHadExist')
        else:
            video_data = {
                'v_id':v_id,
                'title': format_words(parse_param_info(title)),
                'html_cn':cn,
                'html_en': en,
                'html_tw': tw,
                'create_time':str(time.time()),
                'link':format_words(parse_param_info(link)),
                'format_time': FormatIO().timestamp_format(time.time()),
                'create_admin':a_id,
                'status':status
            }
            if mgOp.insert_one(dbNameDict['videoData'], video_data):
                return responseJson.correct(code='ok', data={'msg':'新增视频成功'})
            else:
                return responseJson.error_response(code='unknownError')

    @allow_cross
    def get(self):
        '''
            获取视频信息
        :return:
        '''
        args = parsers()
        v_id = args.get('v_id')
        pg = args.get('pg')
        num = args.get('num')
        status = args.get('status')
        start_t = args.get('start_t')
        end_t = args.get('end_t')

        if v_id:      # 获取单个视频信息
            rd = mgOp.find_one(dbNameDict['videoData'], filter={'v_id':v_id})
            if rd:
                return responseJson.correct(code='ok', data=rd)     # 正确
            else:
                return responseJson.error_response(code='resourcesDoNotExist')    # 视频不存在
        else:
            if not pg:
                pg = 1
            pg = int(pg)
            if not num:
                num = 24
            num = int(num)
            pg = int(pg)
            filter = {}
            if start_t:
                filter['create_time']["$gte"] = str(time.mktime(time.strptime(start_t, "%Y-%m-%d-%H:%M:%S")))
            if end_t:
                filter['create_time']["$lte"]  = str(time.mktime(time.strptime(end_t, "%Y-%m-%d-%H:%M:%S")))
            if status:
                filter['news_status'] = status
            rds = mgOp.find_many(dbNameDict['videoData'], filter=filter)[(pg-1)*num:pg*num]
            if rds:
                for rd in rds:
                    rd['create_admin'] = rd['create_admin']
                return responseJson.correct(code='ok', data=rds)
            else:
                return responseJson.error_response(code='resourcesDoNotExist')   # 视频不存在

    @allow_cross
    def post(self):
        '''
            修改视频信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_id = args.get('w_id')

        link = args.get('link')   # 视频链接
        title = args.get('title')  # 视频标题
        intro = args.get('intro')   # 视频介绍
        status = args.get('status')  # 视频状态

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanModifyVideo', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        new_video_data = {}
        if link:
            new_w_id = cId.vid(link)   # 视频地址变化则视频编号变化
            new_video_data['w_id'] = new_w_id
            new_video_data['link'] = link
        if title:
            new_video_data['title'] = format_words(parse_param_info(title))
        if intro:
            new_video_data['intro'] = format_words(parse_param_info(intro))
        if status:
            new_video_data['status'] = status
        if new_video_data:
            if mgOp.update_one(dbNameDict['videoData'], filter={'w_id':w_id}, data=new_video_data):
                return responseJson.correct(code='ok', data={'msg':'修改视频信息成功'})
            else:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

    @allow_cross
    def delete(self):
        '''
            删除视频信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_id = args.get('w_id')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDeleteVideo', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if mgOp.delete_one(dbNameDict['videoData'], filter={'w_id':w_id}):
            return responseJson.correct(code='ok', data={'msg':'删除视频信息成功'})
        else:
            return responseJson.error_response(code='unknownError')




